package cn.itsource.hrm.web.controller;

import cn.itsource.hrm.util.AjaxResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

//文件上传
@RestController
@RequestMapping("/file")
public class FileController {


    //读取配置
    private String accessId = "LTAI5tB5PcmEgjTsrH187qSh";
    private String accessKeySecret = "h5E6NoZOfWzr2MqHQTiwHXtbpuLKLB";
    private String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
    private String bucket = "itsource-xx";


    /**
     * 签名
     */

    @GetMapping("/sign")
    public AjaxResult sign(){

        // host的格式为 bucketname.endpoint
        String host = "https://" + bucket + "." + endpoint;

        // 用户上传文件时指定的前缀。
        String dir = "itsource";

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKeySecret);

        try {
            long expireTime = 100;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);



            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            return AjaxResult.me().setResultObj(respMap);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return AjaxResult.me();
    }

}
